package com.kyg.tjtoolmanager.net.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import javafx.application.Platform;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;

public class HttpService {

    private static final MediaType mtJSON
            = MediaType.parse("application/json; charset=utf-8");
    private static String authorizationHead = "";
    private volatile static HttpService INSTANCE;
    private volatile static OkHttpClient mOkHttpClient;
//    private static String baseurl;

    private HttpService() {
        mOkHttpClient = new OkHttpClient();

//        Preferences preferences = Preferences.userRoot().node(Constant.Preferences_Node);
//        baseurl = preferences.get("baseurl", "");
//        authorizationHead = preferences.get("authorizationHead", "");

    }


    public static HttpService getInstance() {
        if (INSTANCE == null) {
            synchronized (HttpService.class) {
                if (INSTANCE == null) {
                    INSTANCE = new HttpService();
                }
            }
        }
        return INSTANCE;
    }


    /**
     * 异步get请求
     *
     * @param uri
     * @param map
     * @param callback
     */
    public void httpGet(String uri, Map<String, String> map, HttpBack callback) {
        if (map != null && map.size() != 0) {
            uri = uri + "?";
            for (String in : map.keySet()) {
                String str = map.get(in);
                uri = uri + in + "=" + str + "&";
            }
            uri = uri.substring(0, uri.length() - 1);
        }

        Request request = new Request.Builder()
//                .addHeader("authorization", authorizationHead)
                .url(uri)
                .get().build();
        Call call = mOkHttpClient.newCall(request);
        callListener(call, callback);
    }

    /**
     * 异步Post键值对请求
     *
     * @param uri
     * @param map
     * @param callback
     */
    public void httpPostMap(String uri, Map<String, String> map, HttpBack callback) {
        FormBody.Builder builder = new FormBody.Builder();
        for (String in : map.keySet()) {
            builder.add(in, map.get(in));
        }
        RequestBody body = builder.build();
        Request request = new Request.Builder()
                .addHeader("authorization", authorizationHead)
                .url(uri)
                .post(body).build();
        Call call = mOkHttpClient.newCall(request);
        callListener(call, callback);
    }

    /**
     * 异步Post Bean请求
     *
     * @param uri
     * @param Bean
     * @param callback
     * @param <T>
     */
    public <T> void httpPostBean(String uri, T Bean, HttpBack callback) {
        RequestBody body = RequestBody.create(mtJSON, JSONObject.toJSONString(Bean));
        Request request = new Request.Builder()
                .addHeader("authorization", authorizationHead)
                .url(uri)
                .post(body).build();
        Call call = mOkHttpClient.newCall(request);
        callListener(call, callback);
    }


    private void callListener(Call call, HttpBack httpBack) {

        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                Platform.runLater(() -> {
                    httpBack.onFail(call, e.getMessage());
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    Platform.runLater(() -> {
                        try {
                            HttpEntity httpEntity = JSON.parseObject(response.body().string(), HttpEntity.class);
                            httpBack.onSuccess(call, httpEntity);
                        } catch (IOException e) {
                            e.printStackTrace();
                            httpBack.onFail(call, e.getMessage());
                        }
                    });
                } else {
                    Platform.runLater(() -> {
                        httpBack.onSuccess(call, new HttpEntity(response.message()));
                    });
                }
            }
        });
    }

}
